from rest_framework_jwt.utils import jwt_decode_handler
from django.contrib.auth.models import AnonymousUser
from channels.db import database_sync_to_async
from user.models import UserProfile


class JWTAuthMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        query_string = scope.get("query_string", b"").decode()
        token = None

        # 解析查询参数中的token
        print('中间件query',query_string)
        for param in query_string.split('&'):
            if param.startswith('token='):
                print('拿到了token')
                token = param.split('=')[1]
                print('token',token)
                break
        if token:
            try:
                # 使用rest_framework_jwt的解码方法
                payload = jwt_decode_handler(token)
                print('payload',payload)
                user = await self.get_user(payload['user_id'])
                scope['user'] = user
            except Exception as e:
                print('token错误',e)
                scope['user'] = AnonymousUser()
        else:
            scope['user'] = AnonymousUser()

        return await self.app(scope, receive, send)

    @database_sync_to_async
    def get_user(self, user_id):
        return UserProfile.objects.get(id=user_id)